import Router from 'koa-router';
import * as path from 'path'
import * as fs from 'fs'
import { koaBody } from 'koa-body';
import { format } from 'date-fns'
import { fileURLToPath } from "url";
import {addToQueue} from '../utils/messageQueue.js'
import { files }  from '../db/models.js'

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const upload = new Router();

upload.post('/', koaBody({
    multipart: true,
    encoding: "gzip",
    formidable: {
        uploadDir: path.join(__dirname, "../uploads"),
        keepExtensions: true, // 保持文件的后缀
        maxFieldsSize: 20 * 1024 * 1024, // 文件上传大小限制
        onFileBegin: (name, file) => {
            // 无论是多文件还是单文件上传都会重复调用此函数
            // 最终要保存到的文件夹目录
            const dirName = format(new Date(), "yyyyMMddhhmmss");
            // const dir = path.join(__dirname, `public/upload/${dirName}`);
            const dir = path.join(__dirname, `../uploads/tmp`);
            // 检查文件夹是否存在如果不存在则新建文件夹
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir);
            }
            // 文件名称去掉特殊字符但保留原始文件名称
            const fileName = `${dirName}_${file.originalFilename.replaceAll(" ", "_")
                    .replace(/[`~!@#$%^&*()|\-=?;:'",<>\{\}\\\/]/gi, "_")}`;
            file.originalFilename = fileName;
            // 覆盖文件存放的完整路径(保留原始名称)
            file.filepath = `${dir}/${fileName}`;
        },
    },
}),async (ctx) => {
    ctx.status = 200;
    ctx.body = { code: 200, msg: "上传成功"};
    const { knowledge_base } = ctx.request.body
    const dir = path.join(__dirname, `../uploads/${knowledge_base}`);
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }
    fs.renameSync(ctx.request.files.file.filepath, path.join(dir, ctx.request.files.file.originalFilename))
    const file = {
        name: ctx.request.files.file.originalFilename,
        path: path.join(dir, ctx.request.files.file.originalFilename),
        knowledgeBase: knowledge_base,
        status: 'queuing',
    }
    await files.create(file)
    addToQueue(file)
});

export default upload;
